//
//  NSObject+CurrentController.swift
//  Poetry
//
//  Created by cheyongzi on 2023/12/14.
//

import UIKit

extension NSObject{
    static var classname: String{
        return String(describing: self)
    }
}

extension NSObject {
    func currentViewController() -> UIViewController? {
        var currentViewController: UIViewController!
        let window = UIApplication.shared.keyWindow
        currentViewController = window?.rootViewController
        return getCurrentViewController(currentViewController)
    }
    
    private func getCurrentViewController(_ viewController: UIViewController?) -> UIViewController? {
        var currentViewController: UIViewController?
        if viewController != nil {
            if viewController is UINavigationController && (viewController as! UINavigationController).topViewController != nil {
                currentViewController = (viewController as! UINavigationController).topViewController
                currentViewController = getCurrentViewController(currentViewController)
            }else if viewController is UITabBarController && (viewController as! UITabBarController).selectedViewController != nil {
                currentViewController = (viewController as! UITabBarController).selectedViewController
                currentViewController = getCurrentViewController(currentViewController)
            }else {
                currentViewController = viewController
                var hasPresentController = false
                while let presentedController = currentViewController?.presentedViewController {
                    hasPresentController = true
                    currentViewController = presentedController
                }
                if hasPresentController {
                    currentViewController = getCurrentViewController(currentViewController)
                }
            }
        }
        return currentViewController
    }
}
